home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18128 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  90 lines

  1. Path: inforamp.net!usenet
  2. From: rmorin@inforamp.net (Randy Charles Morin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Saving the contents of an object to a file
  5. Date: Fri, 19 Apr 1996 03:23:10 GMT
  6. Organization: InfoRamp Inc., Toronto, Ontario (416) 363-9100
  7. Message-ID: <4l6mek$ah3@sam.inforamp.net>
  8. References: <31739D83.5F61@mars.superlink.net>
  9. NNTP-Posting-Host: ts47-12.tor.istar.ca
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Michael Rizzo <rizzom@mars.superlink.net> wrote:
  13. >    I am having a problem saving the contents of an object to a 
  14. >file.  For instance, I have the following code:
  15. >
  16. >int main()
  17. >{
  18. >    A x(10,"JOE"), y;
  19. >    ofstream outf("savefile",ios::binary);
  20. >    outf.write((char*) &x, sizeof x);
  21. >    outf.write((char*) &y, sizeof y);
  22. >    outf.close();
  23. >    return 0;
  24. >}
  25.  
  26. try...
  27. ofstream outf("savefile", ios::binary+ios::out);
  28.  
  29. but this won't work either, because you'd be saving only an int and a
  30. pointer.  The string won't get saved.
  31.  
  32. try the following...
  33.  
  34. class A
  35. {
  36. private:
  37.     int id;
  38.     char *name;
  39. public:
  40.     A(int, char*);
  41.     A();
  42.     ~A();
  43.     char * GetName() {return name;}
  44.     int GetId() {return id;}
  45.     friend ipstream & operator >> ( ipstream &is, MWDeltaFile &p );
  46.     friend opstream & operator << ( opstream &os, const MWDeltaFile &p );
  47. };
  48.  
  49. ofstream & operator << ( opstream &os, const A &r )
  50. {
  51.     r << id << name;
  52. };
  53.  
  54. A::A(int i, char *n)
  55. {
  56.     int temp;
  57.     id = i;
  58.     temp = strlen(n);
  59.     name = new char[temp+1];
  60.     strcpy(name,n);
  61. }
  62.  
  63. A::A()
  64. {
  65.     id = 0;
  66.     name = new char[5];
  67.     strcpy(name, "none");
  68. }    
  69.  
  70. int main()
  71. {
  72.     A x(10,"JOE"), y;
  73.     ofstream outf("savefile",ios::binary+ios::binary+ios::out);
  74.     outf << x << y;
  75.     return 0;
  76. }
  77.  
  78. Hope I've helped
  79.  
  80.  
  81. Agrivar
  82.  
  83. aka Randy Charles Morin,
  84. MiddleWorld SoftWare,
  85. Satisfying Your Bit and Bytes,
  86. Canada 1-800-363-3780 
  87. Other  1-905-279-2087
  88. eMail  rmorin@inforamp.net
  89.  
  90.